package com.huiztech.watersoil.activity;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.huiztech.watersoil.R;
import com.huiztech.watersoil.R.drawable;
import com.huiztech.watersoil.R.id;
import com.huiztech.watersoil.R.layout;
import com.huiztech.watersoil.R.string;
import com.huiztech.watersoil.model.AreaMap;
import com.huiztech.watersoil.model.Stream;
import com.huiztech.watersoil.utils.Convertor;
import com.huiztech.watersoil.utils.DBManager;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.provider.Settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
 * 主界面
 * @author alin
 *
 */
public class MainActivity extends Activity {

	private DBManager dbm;
	private SQLiteDatabase db;

	private Button confirmButton;
	private Button autoXYButton;
	private Button cleaButton;
	private AutoCompleteTextView nameEdit;
	private AutoCompleteTextView codeEdit;
	private EditText latitudeEdit;
	private EditText longitudeEdit;

	private double latitude;
	private double longitude;
	
	private final float deviation = 0.07f;//基于当前坐标加减deviation范围内搜索

	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListener();

	private Dialog mDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置背景颜色
		Resources res = getResources();
		Drawable drawable = res.getDrawable(R.drawable.bgcolor);
		this.getWindow().setBackgroundDrawable(drawable);
		// 自定义标题栏
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_main);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		// 获得控件
		nameEdit = (AutoCompleteTextView) findViewById(R.id.name_edit);
		codeEdit = (AutoCompleteTextView) findViewById(R.id.code_edit);
		latitudeEdit = (EditText) findViewById(R.id.latitude_edit);
		longitudeEdit = (EditText) findViewById(R.id.longitude_edit);
		autoXYButton = (Button) findViewById(R.id.auto_xy_button);
		autoXYButton.setOnClickListener(new clickAutoXY());
		confirmButton = (Button) findViewById(R.id.confirm_button);
		confirmButton.setOnClickListener(new clickConfirm());
		cleaButton = (Button) findViewById(R.id.clear_button);
		cleaButton.setOnClickListener(new clickClear());
		nameEdit.setThreshold(1);
		codeEdit.setThreshold(1);
		// 数据库连接
		dbm = new DBManager(MainActivity.this);
		dbm.openDatabase();
		db = dbm.getDatabase();
		// 流域名称auto complete
		ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(this,
				R.layout.list_item, findAllName());
		nameEdit.setAdapter(arrayAdapter1);
		// 流域代码auto complete
		ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(this,
				R.layout.list_item, findAllCode());
		codeEdit.setAdapter(arrayAdapter2);
		// 百度地图定位
		mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
		mLocationClient.registerLocationListener(myListener); // 注册监听函数
		mLocationClient.setAK("49fe6c0e4a54d668792885b93e6c4089");
		// 设置参数
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");// 返回的定位结果包含地址信息
		option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(1000);// 设置发起定位请求的间隔时间为5000ms
		option.disableCache(true);// 禁止启用缓存定位
		option.setPoiNumber(5); // 最多返回POI个数
		option.setPoiDistance(1000); // poi查询距离
		option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
		mLocationClient.setLocOption(option);
		mLocationClient.start(); // 开启服务
		// 等待搜索
		showRoundProcessDialog(this, R.layout.loading_process_dialog_anim);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			pressAgainExit();
			return true;
		}
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			// 监控/拦截菜单键
			nameEdit.setText("");
			codeEdit.setText("");
			latitudeEdit.setText("");
			longitudeEdit.setText("");
		} else if (keyCode == KeyEvent.KEYCODE_HOME) {
			// 由于Home键为系统键，此处不能捕获，需要重写onAttachedToWindow()
		}
		return super.onKeyDown(keyCode, event);
	}

	// "自动获取坐标"按钮监听器
	class clickAutoXY implements OnClickListener {
		@Override
		public void onClick(View v) {
			// Toast.makeText(getApplicationContext(),latitude+"@"+longitude,Toast.LENGTH_SHORT).show();
			String x = latitude + "";
			String y = longitude + "";
			DecimalFormat format = new DecimalFormat("#0.00");// 设置小数点后两位
			if (format.format(latitude).toString().equals("0.00")
					|| format.format(longitude).toString().equals("0.00")) {
				Toast.makeText(getApplicationContext(), "获取坐标失败，请重新获取",
						Toast.LENGTH_SHORT).show();
			}
			latitudeEdit.setText(format.format(latitude).toString());
			longitudeEdit.setText(format.format(longitude).toString());
		}
	}

	// 显示等待进度
	public void showRoundProcessDialog(Context mContext, int layout) {
		OnKeyListener keyListener = new OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_HOME
						|| keyCode == KeyEvent.KEYCODE_SEARCH) {
					return true;
				}
				return false;
			}
		};
		mDialog = new AlertDialog.Builder(mContext).create();
		mDialog.setOnKeyListener(keyListener);
	}

	// 验证输入信息
	public boolean validate() {
		boolean fill = false;
		if (latitudeEdit.getText().toString().equals("")
				|| longitudeEdit.getText().toString().equals("")) {
			fill = false;
		}
		if (!nameEdit.getText().toString().equals("")) {
			fill = true;
		}
		if (!codeEdit.getText().toString().equals("")) {
			fill = true;
		}
		if (!latitudeEdit.getText().toString().equals("")
				&& !longitudeEdit.getText().toString().equals("")) {
			fill = true;
		}
		if (nameEdit.getText().toString().equals("")
				&& codeEdit.getText().toString().equals("")
				&& latitudeEdit.getText().toString().equals("")
				&& longitudeEdit.getText().toString().equals("")) {
			fill = false;
		}
		if (fill) {
			return true;
		} else {
			return false;
		}

	}

	// "确定查询"button监听器
	class clickConfirm implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (validate()) {
				mDialog.show();
				mDialog.setContentView(R.layout.loading_process_dialog_anim);
			} else {
				Toast.makeText(getApplicationContext(), "请输入任意一项",
						Toast.LENGTH_SHORT).show();
			}
			// 新建一个线程负责耗时的查询操作
			new Thread() {
				public void run() {
					String stream_name = nameEdit.getText().toString();
					String stream_code = codeEdit.getText().toString();
					String stream_latitude = latitudeEdit.getText().toString();
					String stream_longitude = longitudeEdit.getText()
							.toString();

					// 根据流域名称查询
					if (validate()) {
						ArrayList<Stream> stream_list = query(stream_name,
								stream_code, stream_latitude, stream_longitude);
						// 如果只有一个查询结果//客户修改了需求
//						if (stream_list.size() == 1) {
//							Intent intent = new Intent();
//							intent.putExtra("stream", stream_list.get(0));
//							intent.setClass(MainActivity.this,
//									com.huiztech.watersoil.DetailActivity.class);
//							mDialog.cancel();
//							startActivity(intent);
//						} else {
							Intent intent = new Intent();
							intent.putExtra("stream_list", stream_list);
							intent.setClass(
									MainActivity.this,
									com.huiztech.watersoil.activity.ListViewActivity.class);
							mDialog.cancel();
							startActivity(intent);
						//}
					}
				}
			}.start();

		}
	}
	/** 清空按钮*/
	public class clickClear implements OnClickListener{

		@Override
		public void onClick(View v) {
			nameEdit.setText("");
			codeEdit.setText("");
			latitudeEdit.setText("");
			longitudeEdit.setText("");
		}
	}

	// 综合查询
	public ArrayList<Stream> query(String stream_name, String stream_code,
			String stream_latitude, String stream_longitude) {
		ArrayList<Stream> stream_list = new ArrayList<Stream>();
		try {
			StringBuffer sqlBuffer = new StringBuffer();
			sqlBuffer.append("select * from stream where (id != '0') ");
			if (!stream_name.equals("")) {
				sqlBuffer.append(" and name = ");
				sqlBuffer.append("'" + stream_name + "'");
			}
			if (!stream_code.equals("")) {
				sqlBuffer.append(" and code = ");
				sqlBuffer.append("'" + stream_code + "'");
			}
			if (!stream_latitude.equals("") && !stream_longitude.equals("")) {
				float longitudeFloat = Float.parseFloat(stream_longitude);
				float latitudeFloat = Float.parseFloat(stream_latitude);
				
				//根据区域范围方法
				sqlBuffer.append(" and ");
				sqlBuffer.append("(longitude between " +(longitudeFloat-deviation));
				sqlBuffer.append(" and ");
				sqlBuffer.append("("+(longitudeFloat+deviation)+"))");
				sqlBuffer.append(" and ");
				sqlBuffer.append("(latitude between " +(latitudeFloat-deviation));
				sqlBuffer.append(" and ");
				sqlBuffer.append("("+(latitudeFloat+deviation)+"))");
				
//				//根据从前匹配的方法
//				sqlBuffer.append(" and latitude like ");
//				sqlBuffer.append("'" + stream_latitude + "%'");
//				sqlBuffer.append(" and longitude like ");
//				sqlBuffer.append("'" + stream_longitude + "%'");
			}
			//System.out.println("sql:" + sqlBuffer.toString());
			Cursor cursor = db.rawQuery(sqlBuffer.toString(), null);
			while (cursor.moveToNext()) {
				// get from database
				int id = cursor.getInt(cursor.getColumnIndex("id"));
				String name = cursor.getString(cursor.getColumnIndex("name"));
				String rainfall = cursor.getString(cursor.getColumnIndex("rainfall"));
				String area = cursor.getString(cursor.getColumnIndex("area"));
				String code = cursor.getString(cursor.getColumnIndex("code"));
				String longitude = cursor.getString(cursor
						.getColumnIndex("longitude"));
				String latitude = cursor.getString(cursor
						.getColumnIndex("latitude"));
				String ar = cursor.getString(cursor.getColumnIndex("ar"));
				String br = cursor.getString(cursor.getColumnIndex("br"));
				String aby = cursor.getString(cursor.getColumnIndex("aby"));
				String bby = cursor.getString(cursor.getColumnIndex("bby"));
				String ay = cursor.getString(cursor.getColumnIndex("ay"));
				String by = cursor.getString(cursor.getColumnIndex("by"));
				String aj = cursor.getString(cursor.getColumnIndex("aj"));
				String bj = cursor.getString(cursor.getColumnIndex("bj"));
				String an = cursor.getString(cursor.getColumnIndex("an"));
				String bn = cursor.getString(cursor.getColumnIndex("bn"));

				String s = cursor.getString(cursor.getColumnIndex("s"));
				String p1 = cursor.getString(cursor.getColumnIndex("p1"));
				String p2 = cursor.getString(cursor.getColumnIndex("p2"));
				String q1 = cursor.getString(cursor.getColumnIndex("q1"));
				String q2 = cursor.getString(cursor.getColumnIndex("q2"));
				String q3 = cursor.getString(cursor.getColumnIndex("q3"));
				String q4 = cursor.getString(cursor.getColumnIndex("q4"));
				String q5 = cursor.getString(cursor.getColumnIndex("q5"));
				// set model
				Stream stream = new Stream();
				stream.setId(id);
				stream.setName(name);
				stream.setRainfall(rainfall);
				stream.setArea(area);
				//System.out.println("所属地区： "+new Convertor().convertByCode(code));
				stream.setCounty(new Convertor().convertByCode(code));
				stream.setCode(code);
				String firstFiveCode = code.substring(0, 5);
				String firstSixCode = code.substring(0, 6);
				String sql2 = "select country_name from country_code where country_code ="+firstFiveCode+" or country_code ="+firstSixCode;
				System.out.println(sql2);
				Cursor cursor2 = db.rawQuery(sql2, null);
				while (cursor2.moveToNext()) {
					String village_name = cursor2.getString(cursor2.getColumnIndex("country_name"));
					stream.setVillage_name(village_name);
				}
				stream.setLatitude(Double.parseDouble(latitude));
				stream.setLongitude(Double.parseDouble(longitude));

				stream.setAr(Float.parseFloat(ar));
				stream.setBr(Float.parseFloat(br));
				stream.setAby(Float.parseFloat(aby));
				stream.setBby(Float.parseFloat(bby));
				stream.setAy(Float.parseFloat(ay));
				stream.setBy(Float.parseFloat(by));
				stream.setAj(Float.parseFloat(aj));
				stream.setBj(Float.parseFloat(bj));
				stream.setAn(Float.parseFloat(an));
				stream.setBn(Float.parseFloat(bn));

				stream.setS(Float.parseFloat(s));
				stream.setP1(Float.parseFloat(p1));
				stream.setP2(Float.parseFloat(p2));
				stream.setQ1(Float.parseFloat(q1));
				stream.setQ2(Float.parseFloat(q2));
				stream.setQ3(Float.parseFloat(q3));
				stream.setQ4(Float.parseFloat(q4));
				stream.setQ5(Float.parseFloat(q5));
				stream_list.add(stream);
				if (cursor.isLast()) {
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stream_list;
	}
	
	// 查询出所有流域名称
	public ArrayList<String> findAllName() {
		ArrayList<String> stream_name_list = new ArrayList<String>();
		try {
			String sql = "select name from stream";
			Cursor cursor = db.rawQuery(sql, null);
			cursor.moveToFirst();
			while (!cursor.isLast()) {
				String name = cursor.getString(cursor.getColumnIndex("name"));
				stream_name_list.add(name);
				cursor.moveToNext();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stream_name_list;
	}

	// 查找出所有流域代码
	public ArrayList<String> findAllCode() {
		ArrayList<String> stream_code_list = new ArrayList<String>();
		try {
			String sql = "select code from stream";
			Cursor cursor = db.rawQuery(sql, null);
			cursor.moveToFirst();
			while (!cursor.isLast()) {
				String code = cursor.getString(cursor.getColumnIndex("code"));
				stream_code_list.add(code);
				cursor.moveToNext();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stream_code_list;
	}

	// 开启GPS提示
	@SuppressWarnings("unused")
	private void openGPSSettings() {
		LocationManager alm = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT).show();
			return;
		}
		Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
		startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
	}

	// 自定义百度LocationListener
	public class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
			}
			if (location.hasAddr()) {

			}
			latitude = location.getLatitude();
			longitude = location.getLongitude();
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
			StringBuffer sb = new StringBuffer(256);
			sb.append("Poi time : ");
			sb.append(poiLocation.getTime());
			sb.append("\nerror code : ");
			sb.append(poiLocation.getLocType());
			sb.append("\nlatitude : ");
			sb.append(poiLocation.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(poiLocation.getLongitude());
			sb.append("\nradius : ");
			sb.append(poiLocation.getRadius());
			if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("\naddr : ");
				sb.append(poiLocation.getAddrStr());
			}
			if (poiLocation.hasPoi()) {
				sb.append("\nPoi:");
				sb.append(poiLocation.getPoi());
			} else {
				sb.append("noPoi information");
			}
		}
	}

	// =============================================================================================
	// Back Event handle
	// =============================================================================================
	class Exit {
		private boolean isExit = false;
		private Runnable task = new Runnable() {
			@Override
			public void run() {
				isExit = false;
			}
		};

		public void doExitInOneSecond() {
			isExit = true;
			HandlerThread thread = new HandlerThread("doTask");
			thread.start();
			new Handler(thread.getLooper()).postDelayed(task, 1000);
		}

		public boolean isExit() {
			return isExit;
		}

		public void setExit(boolean isExit) {
			this.isExit = isExit;
		}
	}

	Exit exit = new Exit();

	/**
	 * press again to exit the program。
	 */
	private void pressAgainExit() {
		if (exit.isExit()) {
			finish();
		} else {
			Toast.makeText(getApplicationContext(),
					getResources().getString(R.string.ExitAppToast), 1000)
					.show();
			exit.doExitInOneSecond();
		}
	}
}
